package com.ityuwen.mengyagushi.user.login;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ityuwen.mengyagushi.account.client.UserAccountFeignClient;
import com.ityuwen.mengyagushi.common.constant.KafkaConstant;
import com.ityuwen.mengyagushi.common.constant.RedisConstant;
import com.ityuwen.mengyagushi.common.service.KafkaService;
import com.ityuwen.mengyagushi.model.user.UserInfo;
import com.ityuwen.mengyagushi.user.mapper.UserInfoMapper;
import com.ityuwen.mengyagushi.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@BeanType(LoginType.WEIXIN)
public class WxLogin implements ILogin{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private KafkaService kafkaService;

    @Override
    public Map<String, Object> login(Map<String, Object> map) {
        try {
            // 调用微信登录的接口，获取响应信息
            String code = map.get("code").toString();
            WxMaJscode2SessionResult sessionInfo = this.wxMaService.getUserService().getSessionInfo(code);

            // 获取OpenId（Session_key 会话密钥，不要使用）
            String openid = sessionInfo.getOpenid();

            // 查询mysql
            UserInfo userInfo = this.userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));

            // 判断查询结构是否为空，如果为空则隐式注册新用户
            if (userInfo == null){
                // 新增用户
                userInfo = new UserInfo();
                userInfo.setWxOpenId(openid);
                userInfo.setNickname("这家伙很懒" + IdWorker.getIdStr());
                userInfo.setAvatarUrl("https://img.touxiangwu.com/uploads/allimg/2022040509/bs5oegv1dc4.jpg");
                userInfo.setStatus("1");
                this.userInfoMapper.insert(userInfo);

                // 初始化账户
//                this.userAccountFeignClient.saveUserAccount(userInfo.getId());
//				int i = 1/0;

                // 发送消息给kafka，将来account获取消息完成账户信息的保存
                this.kafkaService.sendMsg(KafkaConstant.QUEUE_USER_REGISTER, userInfo.getId().toString());
            }

            // 生成token，保存到redis，并响应给浏览器（保存到localStorage）
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(userInfo, userInfoVo);
            this.redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
            // 响应给浏览器
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            return resultMap;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("微信登录失败！");
    }
}
